/**
 * @param {string[]} words
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
export var findClosest = function (words, word1, word2) {
  if (word1 === word2) return 0
  let [index1, index2] = [-1, -1]
  let ans = Number.MAX_SAFE_INTEGER
  for (let i = 0; i < words.length; i++) {
    if (words[i] === word1) {
      index1 = i
    } else if (words[i] === word2) {
      index2 = i
    }
    if (index1 !== -1 && index2 !== -1) {
      ans = Math.min(ans, Math.abs(index1 - index2))
    }
  }
  return ans
}

// 进阶：

const fileWordMap = new Map()

function getWordMap(words) {
  if (fileWordMap.has(words)) {
    return fileWordMap.get(words)
  }
  const wordMap = new Map()
  for (let i = 0; i < words.length; i++) {
    const word = words[i]
    if (!wordMap.has(word)) {
      wordMap.set(word, [])
    }
    wordMap.get(word).push(i)
  }
  fileWordMap.set(words, wordMap)
  return wordMap
}

/**
 * @param {string[]} words
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
export var findClosestEx = function (words, word1, word2) {
  if (word1 === word2) return 0
  const wordMap = getWordMap(words)
  if (!wordMap.has(word1) || !wordMap.has(word2)) {
    return -1
  }
  const w1 = wordMap.get(word1)
  const w2 = wordMap.get(word2)
  let ans = Math.abs(w1[0] - w2[0])
  let [i, j] = [0, 0]
  while (i < w1.length && j < w2.length) {
    ans = Math.min(ans, Math.abs(w1[i] - w2[j]))
    if (w1[i] < w2[j]) {
      i++
    } else {
      j++
    }
  }
  return ans
}
